package com.study.mvc.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.study.mvc.action.base.Action;
import com.study.mvc.bean.base.ActionForm;
import com.study.mvc.utils.FullBean;
import com.study.mvc.utils.XmlBean;

public class ActionServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("GBK");
		response.setCharacterEncoding("GBK"); 
		
		try {
			
			String path=this.getPath(request.getServletPath());
			
			Map<String,XmlBean> map=(Map<String,XmlBean>)this.getServletContext().getAttribute("struts");
			 
			XmlBean xml=map.get(path);
			String formclass=xml.getFormClass();
			String actionCalss=xml.getActionType();
			 
			ActionForm form= FullBean.getForm(formclass,request);
			
//		    Action action=ActionMapping.getAction(actionCalss,request);
			Action action=null;
			String url="";
			try {
				
				Class clazz=Class.forName(actionCalss);
				action=(Action) clazz.newInstance();
				url=action.excute(request,response, form, xml.getActionForward());
			} catch (Exception e) {
				e.printStackTrace();// TODO: handle exception
			}
		    
			RequestDispatcher dispatch=request.getRequestDispatcher(url);
			dispatch.forward(request, response);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

	
	public void init() throws ServletException { 
	}

	public String getPath(String servletpath){
		return servletpath.split("\\.")[0];
	}
}
